<?php
/**
 * Created by PhpStorm.
 * User: Jason
 * Date: 2017/8/26
 * Time: 14:50
 */

namespace Api\Provider\Admin;


use Api\Provider\IndexProvider;
use Api\Service\UserMemberService;
use Api\Service\WxOrderService;
use Common\Util\HttpClient;
use Think\Log;
class OrderProvider extends IndexProvider
{
    /**
     * 生成微信支付接口参数
     * @param $param
     */
    public function wxPayment($param)
    {
        $service = new WxOrderService();
        try {
            $service->validateParam($param);
        } catch (\Exception $e) {
            $this->fail(600, null, array($e->getMessage()));
        }

        //生成预支付订单
        $unifiedorder = $service->unifiedorder($param);

        $xmlData = $service->arrayToXml($unifiedorder);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $returnData = HttpClient::post($url, $xmlData);
        //校验返回的结果并转换为数组
        try {
            $returnData = $service->decryptData($returnData);
        } catch (\Exception $e) {
            $this->fail(600, null, array($e->getMessage()));
        }

        //获取prepay_id
        $prepay_id = $returnData['prepay_id'];
        //生成微信支付请求参数
        $requestPayment = $service->wxPayment($prepay_id);

        $this->success($requestPayment);
    }

    /**
     * 响应微信支付结果通知
     * @param $param
     * @return bool
     */
    public function replyNotify($param)
    {
        Log::writeInfo('start to process Weixin response','wxReply');
        //获取xml数据
        $postXml = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信参数
        if (empty($postXml)) {
            return false;
        }
        //step-1 : 验证签名是否一致
        Log::writeInfo('step-1: validate sign','wxReply');
        $service = new wxOrderService();
        $returnData = $service->xmlToArray($postXml);
        $wx_sign = $returnData['sign'];
        Log::writeInfo('wxPostParam: '.json_encode($returnData), 'wxReply');
        unset($returnData['sign']);
        $valid_sign = $service->sign($returnData);
        if ($wx_sign == $valid_sign) {
            Log::writeInfo('validate sign pass, sign: '.json_encode($wx_sign),'wxReply');
            //更新订单状态
            $id = $service->updateOrder($returnData);
            if ($id === false) {
                $reply['return_code'] = 'FAIL';
                $reply['return_msg'] = '订单号错误';
            } elseif ($id === 0) {
                $reply['return_code'] = 'FAIL';
                $reply['return_msg'] = '订单金额不一致';
            } elseif ($id) {
                $reply['return_code'] = 'SUCCESS';
                $reply['return_msg'] = 'OK';
            }
        } else {
            Log::writeInfo('validate sign no pass! wx_sign: '.json_encode($wx_sign).'; valid_sign: '.json_encode($valid_sign), 'wxReply');
            $reply['return_code'] = 'FAIL';
            $reply['return_msg'] = '签名失败';
        }
        Log::writeInfo('reply message: ' . json_encode($reply),'wxReply');
        $reply = $service->arrayToXml($reply);
        echo $reply;
    }

    /**
     * 获取会员收费设置
     */
    public function coinCharge($param)
    {
        $service = new UserMemberService();
        $chargeSet = $service->coinCharge($param);
        if ($chargeSet) {
            $this->success($chargeSet);
        } else {
            $this->success(array());
        }
    }

    /**
     * 定时任务，每天减少一枚金币
     */
    public function reduceOneCoin()
    {
        $model = M('UserCoinWallet');
        $map = array(
            'amount' => array('gt', 0)
        );
        $list = $model->where($map)->select();
        if (!empty($list)) {
            $model->where($map)->setDec('amount');  //扣除金币
            $model->where($map)->setInc('member_days');  //增加会员成长天数

            //校验会员等级是否满足提升条件
            $umlModel = M('UserMemberLevels');
            foreach ($list as $key => $val) {
                $set = $umlModel->where(['level' => $val['member_level']])->find();
                if ($val['member_days'] >= $set['member_days'] && $val['sheet_click'] >= $set['sheet_click']) {
                    $model->where(['user_id' => $val['user_id']])->setInc('member_level');
                    //todo 触发升级通知
                }
            }

            Log::writeInfo('Reduce all member one coin. UserList:'.json_encode($list),'coinPayment');
            //记录流水
            $userIds = array_column($list, 'user_id');
            $service = new UserMemberService();
            foreach ($userIds as $id) {
                $time = date('YmdHis',time());
                $ids[] = $service->updateUserPayment($id, -1, 2, $time, 200, '');
            }
            $this->success($ids);
        }
    }
}